<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog top="20px" v-model="dialogVisible" :title="dialogType === 'add' ? '新增产品' : '编辑产品'" width="800"
            destroy-on-close>
            <el-form :model="formData" ref="formRef" :rules="rules">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="产品名称" prop="name">
                            <el-input v-model="formData.name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">

                        <el-form-item label="产品SPU" prop="spu_id">
                            <el-select :disabled="dialogType === 'edit'" @change="getprodChange"
                                v-model="formData.spu_id" placeholder="请选择" :loading="isLoadingSpu" filterable
                                clearable>
                                <el-option v-for="item in supArray" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                                <template #empty>
                                    <div class="empty-text">
                                        {{ isLoadingSpu ? '加载中...' : '暂无数据' }}
                                    </div>
                                </template>
                            </el-select>
                        </el-form-item>

                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="产品编码" prop="no">
                            <el-input :disabled="dialogType === 'edit'" v-model="formData.no"
                                placeholder="产品编码请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="采购单位" prop="measure_unit_id">
                            <el-select :disabled="dialogType === 'edit'" v-model="formData.measure_unit_id"
                                placeholder="请选择">
                                <el-option v-for="item in unitOptions" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>

                        </el-form-item>
                    </el-col>


                </el-row>
                <el-row :gutter="20">

                    <el-col :span="12">

                        <el-form-item label="拆零" prop="open_unit_num">
                            <el-input :disabled="dialogType === 'edit'" type="number" v-model="formData.open_unit_num"
                            @input="handleOpenUnitNumInput"    placeholder="请输入" style="flex: 1; margin-right: 10px;" />

                            <el-select style="width: 120px;" :disabled="dialogType === 'edit'"
                                v-model="formData.open_unit_id" placeholder="请选择" clearable>
                                <el-option v-for="item in openUnitOptions" :key="item.id" :label="item.name"
                                    :value="String(item.id)">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>


                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="formData.status" placeholder="请选择">
                                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">

                    <el-col :span="12">
                        <!-- <el-form-item label="规格型号">
                            <el-input v-model="formData.spec" placeholder="请输入"></el-input>
                        </el-form-item> -->
                        <el-form-item label="拆零规格" prop="unit_num">
                            <el-input type="number" style="flex: 1; margin-right: 10px;"
                              @input="handleUnitNumInput" :disabled="dialogType === 'edit'" v-model="formData.unit_num"
                                placeholder="规格请输入"></el-input>

                            <el-select style="width: 120px;" :disabled="dialogType === 'edit'"
                                v-model="formData.spu_measure_unit_id" placeholder="请选择" clearable>
                                <el-option v-for="item in SpecificationUnit" :key="item.id" :label="item.name"
                                    :value="String(item.id)">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="型号">
                            <el-input :disabled="dialogType === 'edit'" v-model="formData.specification"
                                placeholder="请输入"></el-input>
                        </el-form-item>

                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="单价（元）" prop="price">
                            <el-input @input="handlePriceInput" v-model="formData.price" placeholder="请输入" type="number">
                                <template #suffix>
                                    <span v-if="getSelectedUnitName()" style="color: #909399; font-size: 12px;">/ {{ getSelectedUnitName() }}</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="供应商">
                            <!-- 可多选 -->
                            <el-select multiple v-model="formData.supplier_ids" placeholder="请选择">
                                <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="成本价（元）">
                            <el-input v-model="formData.cost_price" placeholder="请输入" type="number"></el-input>
                        </el-form-item>

                    </el-col> -->
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="formData.note" placeholder="请输入"></el-input>
                        </el-form-item>


                    </el-col>
                    <el-col :span="12">

                        <el-form-item label="是否默认(补库产品)">
                            <el-switch style="margin-top: 10px;" v-model="formData.is_default" :active-value="1"
                                :inactive-value="-1" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                </el-row>



                <el-form-item label="产品照片">
                    <div class="upload-container">
                        <span class="upload-tip">（最多上传6张图片，单张大小在200kb以内）</span>
                        <el-upload v-model:file-list="imageList" :limit="6" accept=".jpg, .jpeg, .png"
                            list-type="picture-card" :on-preview="handlePictureCardPreview"
                            :on-success="handlePictureCardSuccess" :action="uploadUrl" :on-remove="handleRemove"
                            :before-upload="beforeUpload">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>

                        <el-dialog v-model="dialogImageVisible" width="600px">
                            <img w-full :src="dialogImageUrl" alt="预览图" style="width: 100%;height: 100%;" />
                        </el-dialog>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" color="#626aef">确认</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, defineEmits, defineProps, defineExpose, onMounted, nextTick } from "vue";
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { usePublicDataStore } from "@/stores/publicData"; // 导入 store
import api from "@/api";
import { dataType, ApiResponse } from "@/utils/publicType";
import http from "@/utils/http";
//空数据
const emptyData = {
    id: '',
    name: '',
    no: '',
    specification: '',
    measure_unit_id: '',
    spu_measure_unit_id: '',
    open_unit_id: '',
    price: '',
    open_unit_num: '',
    status: 1, // 默认启用
    unit_num: 0,
    note: '',
    spu_id: '',
    supplier_ids: '',
    img: [],
    is_default: 1,
}

// 表单数据
let formData = reactive({
    id: '',
    name: '',
    no: '',
    specification: '',
    measure_unit_id: '',
    spu_measure_unit_id: '',
    open_unit_id: '',
    open_unit_num: '',
    price: 0,
    status: 1, // 默认启用
    unit_num: 0,
    note: '',
    spu_id: '',
    supplier_ids: '',
    img: [] as string[],
    is_default: 1,
});

const publicDataStore = usePublicDataStore();
// 接收父组件传入的值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogType: {
        type: String,
        default: 'add'
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    },

    TreeId: {
        type: Number,
        default: 0
    },

    departmentTree: {
        type: Array,
        default: () => []
    },

});

interface DepartmentTree {
    id: number;
    name: string;
    parent_id: number;
}

const departmentTreeData = ref<DepartmentTree[]>(props.departmentTree as DepartmentTree[]);

watch(() => props.departmentTree, (newVal) => {
    if (newVal && Array.isArray(newVal)) {
        departmentTreeData.value = [...newVal] as DepartmentTree[];
    }
}, { deep: true });

const emit = defineEmits(['update:dialogVisible', 'submit', 'cancel']);

// 表单ref
const formRef = ref<FormInstance>();



// 表单验证规则
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
    no: [{ required: true, message: '请输入产品编码', trigger: 'blur' }],
    unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    open_unit_id: [{ required: true, message: '请选择拆零单位', trigger: 'change' }],
    measure_unit_id: [{ required: true, message: '请选择规格单位', trigger: 'change' }],
    open_unit_num: [{ required: true, message: '请输入拆零数量', trigger: 'blur' }],
    unit_num: [{ required: true, message: '请输入规格数量', trigger: 'blur' }],
    price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
});


let hsdw = ref<string>('');
type unitOptions = {
    id: number;
    name: string;
    type: number;
}
// 单位选项
const unitOptions = ref<unitOptions[]>([]);
//规格单位
let SpecificationUnit = ref<unitOptions[]>([]);

//拆零下拉
let openUnitOptions = ref<unitOptions[]>([]);
// 状态选项
const statusOptions = ref([
    { value: 1, label: '已上架' },
    { value: 0, label: '已下架' }
]);

// 图片上传相关
const imageList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref('');
const dialogImageVisible = ref(false);
const uploadUrl = ref(http.baseURL.split('/admin')[0] + '/api/upload');




// 监听对话框显示状态
const dialogVisible = ref(props.dialogVisible);
watch(() => props.dialogVisible, (val) => {
    dialogVisible.value = val;
    if (val) {
  

        // 打开弹窗时获取SPU列表
        getproductList();
        getUnitMeasureList();
        getSupplierList();
        if (props.dialogType === 'edit' && props.dialogRow) {
            // 编辑模式下填充表单数据
            Object.keys(formData).forEach(key => {
                if (key in props.dialogRow) {
                    formData[key] = props.dialogRow[key];
                    if (key == 'open_unit_id') {
                        formData[key] = String(formData[key]);
                    }
                    if (key == 'price') {
                        formData[key] = Number(formData[key]);
                    }
                }
            });
            console.log(formData, 'formData');
            if (formData.spu_measure_unit_id) {
                formData.spu_measure_unit_id = String(formData.spu_measure_unit_id);
            }
            if (formData.spu_id) {
                nextTick(() => {
                    getprodChange(Number(formData.spu_id));
                });
            }
            if (formData.img.length > 0) {
                imageList.value = formData.img.map((item, index) => {
                    return {
                        url: item,
                        name: '图片' + index,
                    }
                })
            }
        } else {
            // 设置默认分组ID为当前选中的分组

        }
    } else {

        for (let key in formData) {
            formData[key] = emptyData[key];
        }
        imageList.value = [];
        // 关闭弹窗时重置hsdw
        hsdw.value = '';
    }
});

// 监听对话框内部状态变化并同步到父组件
watch(dialogVisible, (val) => {
    emit('update:dialogVisible', val);
});


const handlePriceInput = (val: string) => {
    if (Number(val) < 0) {
        formData.price = 0;
    }
}

// 获取选中的采购单位名称
const getSelectedUnitName = () => {
    if (!formData.measure_unit_id || !unitOptions.value.length) {
        return '';
    }
    const selectedUnit = unitOptions.value.find(unit => unit.id === Number(formData.measure_unit_id));
    return selectedUnit ? selectedUnit.name : '';
}

const handleOpenUnitNumInput = (val: string) => {
    if (Number(val) < 0) {
        formData.open_unit_num = '0';
    }
}


const handleUnitNumInput = (val: string) => {
    if (Number(val) < 0) {
        formData.unit_num = 0;
    }
}


// 重置表单
const resetForm = () => {

};

// 取消按钮
const handleCancel = () => {
    dialogVisible.value = false;
    emit('cancel');
};


// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return;
    //拆零单位和规格单位必选
    if (formData.open_unit_id == '') {
        ElMessage.error('拆零单位必选');
        return;
    }
    if (formData.spu_measure_unit_id == '') {
        ElMessage.error('规格单位必选');
        return;
    }

    //过滤输入框的前后空格
    formData.name = formData.name.trim();
    formData.no = formData.no.trim();
    formData.specification = formData.specification.trim();
    formData.note = formData.note.trim();

    await formRef.value.validate(async (valid, fields) => {
        if (valid) {
            // formData.img = ['https://cgj-1309034514.cos.ap-chengdu.myqcloud.com/202506/685ba2d591c26.png']
            formData.unit_num = Number(formData.unit_num);
            console.log(formData, 'formData');
            let res: dataType;

            if (props.dialogType == 'add') {
                res = await api.product.product_add(formData);
            } else {
                res = await api.product.product_edit(formData);
            }


            if (res.code == 200) {
                ElMessage.success(res.message);
                // 将库存上下限数据一并提交
                const submitData = {
                    ...formData,
                };
                emit('submit', submitData);
                dialogVisible.value = false;
            } else {
                ElMessage.error(res.message);
            }

        }
    });
};

// 图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = (file) => {
    dialogImageUrl.value = file.url || '';
    dialogImageVisible.value = true;
};

// 图片上传成功
const handlePictureCardSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    console.log(response, 'response');
    if (response && response.code === 200) {
        formData.img.push(response.data.url);
        ElMessage.success('上传成功');
    } else {
        ElMessage.error('上传失败');
    }
};



// 图片删除
const handleRemove: UploadProps['onRemove'] = (file, fileList) => {


    let index;
    // 类型安全的处理方式
    const fileResponse = file?.response as any;
    if (fileResponse?.data?.url) {
        index = formData.img.findIndex(img => img === fileResponse.data.url);
    } else {
        index = formData.img.findIndex(img => img === file.url);
    }

    if (index !== -1) {
        formData.img.splice(index, 1);
    }
    console.log(formData.img, 'formData.img', file, fileList);
};

// 上传前检查
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    const isImage = /\.(jpg|jpeg|png)$/.test(file.name.toLowerCase());
    const isLt200K = file.size / 1024 < 1000;

    if (!isImage) {
        ElMessage.error('只能上传JPG/JPEG/PNG格式的图片!');
        return false;
    }
    if (!isLt200K) {
        ElMessage.error('图片大小不能超过1MB!');
        return false;
    }
    return true;
};

// 对外暴露方法
defineExpose({
    openDialog: (type: string, row?: any) => {
        if (type === 'edit' && row) {
            Object.keys(formData).forEach(key => {
                if (key in row) {
                    formData[key] = row[key];
                }
            });
        } else {
            resetForm();
        }
        dialogVisible.value = true;
    }
});


interface supArray {
    id: number;
    name: string;
    measure_unit_id: number;
    measure_unit_name: string;
}

let supArray = ref<supArray[]>([]);
let isLoadingSpu = ref<boolean>(false);

// 获取产品SPU列表
const getproductList = async () => {
    isLoadingSpu.value = true;
    try {
        const res: ApiResponse<supArray> = await api.productbasics.getproductList({ page: 'all' });
        if (res.code == 200) {
            supArray.value = res.data
        } else {
            ElMessage.error(res.message || '获取产品SPU列表失败');
        }
    } catch (error) {
        ElMessage.error('获取产品SPU列表异常');
    } finally {
        isLoadingSpu.value = false;
    }
}

// SPU选择变更处理
const getprodChange = (val: number) => {
    if (!val) {
        hsdw.value = ''; // 清空选择时重置hsdw
        return;
    }

    try {
        // 根据选择的SPU ID查找对应的SPU信息
        const selectedSpu = supArray.value.find(item => item.id === val);
        if (selectedSpu) {
            // 可以根据选择的SPU自动填充一些表单字段
            hsdw.value = selectedSpu.measure_unit_name || '';
        }
    } catch (error) {

    }
}
// 获取计量单位列表
const getUnitMeasureList = async () => {
    const res: ApiResponse<unitOptions> = await api.publicFun.getMeasureUnitList();
    if (res.code == 200) {
        let dataArr = res.data;
        unitOptions.value = Array.isArray(dataArr) && dataArr.filter((item) => item.type == 1) || [];
        SpecificationUnit.value = Array.isArray(dataArr) && dataArr.filter((item) => item.type == 2) || [];
        openUnitOptions.value = Array.isArray(dataArr) && dataArr.filter((item) => item.type == 1) || [];
    }
}

type supplierOptions = {
    id: number;
    name: string;
}
let supplierOptions = ref<supplierOptions[]>([]);
// 获取供应商列表
const getSupplierList = async () => {
    const res: dataType = await api.publicFun.getSupplierList();
    if (res.code == 200) {
        supplierOptions.value = res.data as supplierOptions[]
    }
}

</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
    margin-bottom: 6px !important;
}

::v-deep .form-section {
    padding-top: 0px !important;
}

::v-deep .el-form-item__label {
    margin-left: 0px !important;
}

::v-deep .el-form-item__label-wrap {
    margin-left: 0px !important;
}

::v-deep .el-form-item {
    display: block;
}

.empty-text {
    text-align: center;
    padding: 10px 0;
    color: #909399;
    font-size: 14px;
}

.dialog-box {


    .upload-container {
        .upload-tip {
            font-size: 12px;
            color: #999;
        }

        .image-list {
            display: flex;
            flex-wrap: wrap;
            margin-top: 10px;
            gap: 10px;

            .upload-box {
                width: 100px;
                height: 100px;
                border: 1px dashed #d9d9d9;
                border-radius: 4px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                cursor: pointer;

                &:hover {
                    border-color: #409eff;
                }

                .el-icon {
                    font-size: 24px;
                    color: #8c939d;
                    margin-bottom: 5px;
                }

                span {
                    font-size: 12px;
                    color: #8c939d;
                }
            }

            .image-item {
                width: 100px;
                height: 100px;
                position: relative;
                border-radius: 4px;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                .image-actions {
                    position: absolute;
                    top: 0;
                    right: 0;
                    background-color: rgba(0, 0, 0, 0.5);
                    color: #fff;
                    padding: 2px;
                    border-radius: 0 0 0 4px;
                    cursor: pointer;
                }
            }
        }
    }
}

::v-deep .el-dialog {
    --el-dialog-padding-primary: 0px;
}

::v-deep .el-dialog__header {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

::v-deep .dialog-footer {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #000;
}

::v-deep .el-dialog__body {
    padding: 20px 10px;
}
</style>
